package com.niubility.controller;

import com.niubility.entity.Follow;
import com.niubility.entity.Message;
import com.niubility.exception.CustomException;
import com.niubility.server.ILabService;
import com.niubility.server.Impl.FollowServer;
import com.niubility.server.Impl.MessageServer;

import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
@Transactional(rollbackFor = Exception.class)
public class FollowController {
    @Resource
    private FollowServer followServer;
    @Resource
    private MessageServer messageServer;
    @Resource
    private ILabService labService;

    Logger logger = Logger.getLogger(FollowController.class);
    //增加关注
    @RequestMapping("/FollowSaveAll")
    public void SaveAll(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        response.setCharacterEncoding("utf-8");
            Follow follow = new Follow();
            String callback = request.getParameter("callback");
            String result=null;
            int folId = 0;


            if(request.getParameter("folId")!=null){
                folId = Integer.parseInt(request.getParameter("folId"));
            }else{
                try {
                    folId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
                }catch (Exception e){
                    result = callback+"({"+"\"returncode\""+":"+103+"})";
                    try {
                        response.getWriter().write(result);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                throw new CustomException();
            }

            int foledId = Integer.parseInt(request.getParameter("foledId"));

            DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            String date = format.format(new Date());
            follow.setFolId(folId);
            follow.setFoledId(foledId);
            follow.setFolDate(date);
            Message message = new Message();
            message.setMesSendid(folId);
            message.setMesMainid(foledId);
            message.setMesText("You Be Fellowed!");
            message.setMesMark("0");
            message.setMesAssessmark(0);
            message.setMesDate(date);


            try {

                if(foledId>699999999&&foledId<800000000){
                    labService.changeUsernum(foledId,1);
                }
                boolean bool = followServer.Save(follow)>0?true:false;
                boolean bool2 = messageServer.InsertMessage(message)>0?true:false;
                //System.out.println("bool:"+bool+"  "+"bool2:"+bool2);
            }catch (Exception e){
                logger.debug("Operator Error."+e);
                result = callback + "(" + "{\"state\":" + 108 + "})";
                try {
                    response.getWriter().write(result);
                } catch (IOException e1) {
                    logger.debug("error."+e);
                }
                throw new CustomException();
            }
            result = callback + "(" + "{\"state\":" + 100 + "})";
            try {
                response.getWriter().write(result);
            } catch (IOException e) {
                e.printStackTrace();
            }

    }
    @RequestMapping("/FollowDeleteAll")
    //取消关注
     public void DeleteAll(HttpServletRequest request,HttpServletResponse response) throws CustomException {
        response.setCharacterEncoding("utf-8");
        int k = Integer.parseInt(request.getParameter("k"));
        String result;
        if (k == 1) {
            String callback = request.getParameter("callback");
            Follow follow = new Follow();
            int folId = 0;


            if(request.getParameter("folId")!=null){
                folId = Integer.parseInt(request.getParameter("folId"));
            }else{
                try {
                    folId = Integer.parseInt(request.getSession().getAttribute("userId").toString());
                }catch (Exception e){
                    result = callback+"({"+"\"returncode\""+":"+103+"})";
                    try {
                        response.getWriter().write(result);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    throw new CustomException();
                }
            }
            int foledId = Integer.parseInt(request.getParameter("foledId"));

            follow.setFolId(folId);
            follow.setFoledId(foledId);
            int i = 0;

            Message message = new Message();
            message.setMesSendid(folId);
            message.setMesMainid(foledId);
            message.setMesText("The follow is Over!");
            try {

                followServer.Delete(follow);
                if(foledId>699999999&&foledId<800000000){
                    labService.changeUsernum(foledId,-1);
                }
                messageServer.InsertMessage(message);
            }catch (Exception e){
                 result = callback + "(" + "{\"state\":" + 108 + "})";
                try {
                    response.getWriter().write(result);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                throw new CustomException();
            }
             result = callback + "(" + "{\"state\":" + 100 + "})";
            try {
                response.getWriter().write(result);
            } catch (IOException e) {
                logger.debug("Error."+e);
            }
        }
    }
    //获取关注数量
    //test pass
    @RequestMapping("/FollowCount")
    public void FollowCount(HttpServletRequest request,HttpServletResponse response){
        int count=0;
        String callback=request.getParameter("callback");
        int foledId=Integer.parseInt(request.getParameter("foledId"));
        String result=null;
        try {
            count=followServer.FollowCount(foledId);
        }catch (Exception e){
            logger.debug("Error."+e);
            result=callback+"("+"{\"count\":"+count+"})";
        }
        result=callback+"("+"{\"count\":"+count+"})";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
